package com.blockchain.console.service.system.achieve;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.blockchain.common.enums.LoginStatus;
import com.blockchain.console.service.system.SysLoginLogManage;
import com.blockchain.console.service.system.entity.SysLog;
import com.blockchain.console.service.system.query.SysLogQuery;
import com.blockchain.framework.service.ServiceFactory;
import com.blockchain.framework.service.ServiceResource;
import com.blockchain.framework.service.query.ArrayParser;
import com.blockchain.framework.service.query.Paging;
import com.blockchain.framework.service.query.PagingResult;
import com.blockchain.util.StringHelper;
import com.blockchain.util.parser.EnumParser;

public class SysLoginLogManageImpl extends AbstractSystemService implements
		SysLoginLogManage {

	public static class SysLoginLogManageFactory implements
			ServiceFactory<SysLoginLogManage> {

		@Override
		public SysLoginLogManage newInstance(ServiceResource serviceResource) {
			return new SysLoginLogManageImpl(serviceResource);
		}
	}

	public SysLoginLogManageImpl(ServiceResource serviceResource) {
		super(serviceResource);
	}

	@Override
	public PagingResult<SysLog> seacrch(SysLogQuery query, Paging paging)
			throws Throwable {
		String sql = "SELECT F01,F02,F03,F04,F05 FROM T7012 WHERE 1=1";
		StringBuilder sb = new StringBuilder();
		sb.append(sql);
		List<Object> parameters = new ArrayList<>();
		if (query != null) {
			String accountName = query.getAccountName();
			Timestamp createTimeStart = query.getCreateTimeStart();
			Timestamp createTimeEnd = query.getCreateTimeEnd();
			String gjz = query.getGjz();
			if (!StringHelper.isEmpty(accountName)) {
				sb.append(" AND F02 LIKE ?");
				parameters.add(getSQLConnectionProvider().allMatch(accountName));
			}
			if (createTimeStart != null) {
				sb.append(" AND DATE(F03)>=?");
				parameters.add(createTimeStart);
			}
			if (createTimeEnd != null) {
				sb.append(" AND DATE(F03)<=?");
				parameters.add(createTimeEnd);
			}
			if (!StringHelper.isEmpty(gjz)) {
				sb.append(" AND F04 LIKE ?");
				parameters.add(getSQLConnectionProvider().allMatch(gjz));
			}
		}
		sb.append(" ORDER BY F03 DESC");
		return selectPaging(getConnection(),
				new ArrayParser<SysLog>() {

					@Override
					public SysLog[] parse(ResultSet resultSet)
							throws SQLException {
						List<SysLog> lists = new ArrayList<>();
						while (resultSet.next()) {
							SysLog sysLog = new SysLog();
							sysLog.id = resultSet.getInt(1);
							sysLog.accountName = resultSet.getString(2);
							sysLog.lastTime = resultSet.getTimestamp(3);
							sysLog.lastIp = resultSet.getString(4);
							sysLog.isSuccess = EnumParser.parse(
									LoginStatus.class, resultSet.getString(5));
							lists.add(sysLog);
						}
						return lists.toArray(new SysLog[lists.size()]);
					}
				}, paging, sb.toString(), parameters);
	}

}
